import express from "express";
import { renderToString } from "vue/server-renderer";
import { createApp } from "./app.js";

// 创建 express 实例
const server = express();

server.use(express.static("./"));

// 后端路由
server.get("/", (req, res) => {
  // 创建一个 ssr应用实例
  // const app = createSSRApp({
  //   data: () => ({ count: 1 }),
  //   template: `<button @click="count++">{{ count }}</button>`,
  // });

  // 换成使用 与 客户端相同的内容，避免水合警告
  const app = createApp();

  // 将 ssr应用实例 转换成 html字符串，然后输出到浏览器
  renderToString(app).then((html) => {
    res.send(`
    <!DOCTYPE html>
    <html>
      <head>
        <title>Vue SSR Example</title>

        <script type="importmap">
          {
            "imports": {
              "vue": "https://unpkg.com/vue@3/dist/vue.esm-browser.js"
            }
          }
        </script>

        <script type="module" src="/client.js"></script>

      </head>
      <body>
        <div id="app">${html}</div>
      </body>
    </html>
    `);
  });
});

// 监听端口，启动服务
server.listen(3000, () => {
  console.log("ready");
});
